package com.conversationboard.formatter;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 * Export a ResultSet object into CSV format.
 * Based on http://www.rfc-editor.org/rfc/rfc4180.txt
 * 
 * @author Keith Watson
 *
 */

public class CsvExport {

	public String exportCsvAsString(ResultSet resultSet, ResultSetMetaData metaData) throws SQLException {

		List<String> columnNames = new LinkedList<String>();
		StringBuilder buffer = new StringBuilder();

		/* Get the column names into a List for use later */

		for (int i = 1; i < (metaData.getColumnCount() - 1); i++) {
			columnNames.add(metaData.getColumnName(i));
		}

		/* Produce a header, with the column names */

		for (String columnName : columnNames) {
			buffer.append(this.processCell(columnName));
			buffer.append(",");
		}

		/* Replace final comma with a new line */

		this.processEndOfLine(buffer);

		/* Process each row of the result set */

		while (resultSet.next()) {

			for (String columnName : columnNames) {

				String cell = resultSet.getString(columnName);

				if (cell == null) {
					cell = "";
				}

				cell = this.processCell(cell);

				buffer.append(cell);
				buffer.append(",");
			}

			this.processEndOfLine(buffer);
		}

		return buffer.toString();

	}


	/**
	 * Replace the last comma with a new line.
	 * 
	 * @param buffer
	 */

	private void processEndOfLine(StringBuilder buffer) {
		buffer.deleteCharAt(buffer.length() - 1);
		buffer.append("\n");
	}


	/**
	 * Replace all quotes with double quotes and then enclose the whole cell content in quotes.
	 * 
	 * @param cell
	 * @return
	 */

	private String processCell(String cell) {

		cell = cell.replaceAll("\"", "\"\"");
		cell = "\"" + cell + "\"";

		return cell;
	}

}
